#include "urlextracter.h"

#include <QRegExp>


namespace FileTransfer {


UrlExtracter::UrlExtracter(QObject *parent) : QObject(parent)
{
    m_starting = "<p align=\"center\"><a href=\"";
    m_ending = "\"><img src=\"/img/btn_download.gif\" border=\"0\"></a></p>";
    m_reply = 0;
    m_manager = new QNetworkAccessManager(this);
}


UrlExtracter::~UrlExtracter()
{

}


void UrlExtracter::getUrl(const QString &pageUrl)
{
    QRegExp reg("http://*data.cod.ru/*");
    reg.setPatternSyntax(QRegExp::Wildcard);
    if (!reg.exactMatch(pageUrl)) {
        emit done(pageUrl);
        return;
    }
    m_isFirst = true;
    m_isAborted = false;
    QUrl url;
    url.setUrl(pageUrl.toLatin1());
    if (!url.isValid()) {
        emit done(QString());
        return;
    }
    QNetworkRequest request(url);
    request.setRawHeader("User-Agent", "Wget");
    request.setRawHeader("Accept", "*/*");
    request.setRawHeader("Connection", "Keep-Alive");
    m_reply = m_manager->get(request);
    connect(m_reply, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(m_reply, SIGNAL(finished()), this, SLOT(finished()));
}


void UrlExtracter::abort()
{
    m_isAborted = true;
    if (m_reply)
        m_reply->abort();
}


void UrlExtracter::readyRead()
{
    if (m_reply->error() > 0) {
        emit done(QString());
        m_pageData.clear();
        return;
    }
    QByteArray bytes = m_reply->readAll();
    m_pageData.append(bytes);
    if (m_pageData.size() >= 15000) {
        m_isAborted = true;
        m_reply->abort();
    }
}


void UrlExtracter::finished()
{
    if ((m_reply->error() > 0) && (!m_isAborted)) {
        emit done(QString());
        m_pageData.clear();
        return;
    }
    int start = m_pageData.indexOf(m_starting, 0);
    if (start >= 0) {
        start += m_starting.length();
        int end = m_pageData.indexOf(m_ending, start);
        QString href = m_pageData.mid(start, end - start);
        if (!href.isEmpty()) {
            emit done(href);
            m_pageData.clear();
            return;
        }
    }
    emit done(QString());
    m_pageData.clear();
    return;
}

} // namespace FileTransfer
